package service;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/0101")
public class SPSTU extends HttpServlet {

    // 数据库配置
    private static final String DB_URL = "jdbc:mysql://192.168.244.11:3306/stats?serverTimezone=Asia/Shanghai&useSSL=false";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 1. 设置响应头（解决跨域和编码问题）
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
       // resp.setHeader("Access-Control-Allow-Origin", "*");

        // 2. 获取查询参数
        String name = req.getParameter("name");

        try {
            // 3. 查询数据库
            List<StudentRecommendation> recommendations = getCFRecommendations(name);

            // 4. 序列化为JSON（关键修改：确保字段名匹配）
            String json = new ObjectMapper().writeValueAsString(recommendations);
            resp.getWriter().write(json);

            // 5. 打印日志（调试用）
            System.out.println("[Success] 返回数据: " + recommendations);

        } catch (Exception e) {
            resp.setStatus(500);
            resp.getWriter().write("{\"error\":\"服务器异常: " + e.getMessage() + "\"}");
            System.err.println("[Error] 查询失败: " + e.getMessage());
        }
    }

    private List<StudentRecommendation> getCFRecommendations(String name) throws SQLException {


        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        List<StudentRecommendation> recommendations = new ArrayList<>();

        String sql = "SELECT name, semester, predicted_gpa AS gpa " +  // 别名gpa与前端匹配
                "FROM gpa_recommendations1 " +
                (name != null ? "WHERE name LIKE ? " : "") +
                "ORDER BY predicted_gpa DESC LIMIT 3";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            if (name != null) {
                stmt.setString(1, "%" + name + "%");
            }
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                recommendations.add(new StudentRecommendation(
                        rs.getString("name"),
                        rs.getInt("semester"),
                        rs.getDouble("gpa")  // 使用别名gpa
                ));
            }
        }
        return recommendations;
    }

    // 内部类（关键修改：通过@JsonProperty指定字段名）
    public static class StudentRecommendation {
        @JsonProperty("name")  // 确保与前端一致
        private String name;

        @JsonProperty("semester")
        private int semester;

        @JsonProperty("gpa")  // 前端使用gpa字段
        private double predictedGPA;

        public StudentRecommendation(String name, int semester, double predictedGPA) {
            this.name = name;
            this.semester = semester;
            this.predictedGPA = predictedGPA;
        }

        // Getter方法必须存在（Jackson依赖）
        public String getName() { return name; }
        public int getSemester() { return semester; }
        public double getPredictedGPA() { return predictedGPA; }
    }
}